package edu.ynu.se.xiecheng.achitectureclass.project.common;

import edu.ynu.se.xiecheng.achitectureclass.project.dao.DeviceRepository;
import edu.ynu.se.xiecheng.achitectureclass.project.dao.UserRepository;
import edu.ynu.se.xiecheng.achitectureclass.project.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.project.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    @Transactional
    public void run(String... args) throws Exception {
        // 清理重复用户
        cleanupDuplicateUsers();

        // 初始化用户
        initializeUser();

        // 初始化设备
        initializeDevices();
    }

    /**
     * 清理重复用户
     */
    private void cleanupDuplicateUsers() {
        // 查找所有用户名为 "20221120285" 的用户
        List<User> duplicateUsers = userRepository.findAllByUsername("20221120285")
                .map(Collections::singletonList)
                .orElse(Collections.emptyList());

        // 如果存在多个用户，保留第一个，删除其余
        if (duplicateUsers.size() > 1) {
            User userToKeep = duplicateUsers.get(0); // 保留第一个用户
            for (int i = 1; i < duplicateUsers.size(); i++) {
                userRepository.delete(duplicateUsers.get(i)); // 删除其余用户
            }
            logger.info("Deleted duplicate users, kept user with ID: " + userToKeep.getId());
        }
    }

    /**
     * 初始化用户
     */
    private void initializeUser() {
        // 检查用户是否已存在
        Optional<User> userOptional = userRepository.findByUsername("20221120285");
        if (userOptional.isEmpty()) {
            User user = new User();
            user.setUsername("20221120285");
            user.setPassword(passwordEncoder.encode("20221120285"));
            userRepository.save(user);
            logger.info("User initialized: 20221120285");
        } else {
            logger.info("User already exists: 20221120285");
        }
    }

    /**
     * 初始化设备
     */
    private void initializeDevices() {
        // 设备 ID 列表
        List<String> deviceIds = Arrays.asList(
                "327061586065758005", // 土壤含水率
                "327061586065758015", // 土壤温度
                "327061586065758006", // 土壤电导率
                "327061586065758007", // 土壤PH值
                "327061586065758008", // 土壤氮含量
                "327061586065758009", // 土壤磷含量
                "327061586065758010", // 土壤钾含量
                "327061586065758013", // 空气温度
                "327061586065758014", // 空气相对湿度
                "327061586065758012", // 光照度
                "327061586065758011"  // 二氧化碳
        );

        // 检查设备是否已存在
        for (String deviceId : deviceIds) {
            Optional<Device> deviceOptional = deviceRepository.findBySerialNumber(deviceId);
            if (deviceOptional.isEmpty()) {
                Device newDevice = new Device();
                newDevice.setSerialNumber(deviceId);
                newDevice.setName("Sensor " + deviceId);
                newDevice.setCategory("Sensor");
                deviceRepository.save(newDevice);
                logger.info("Device initialized: " + deviceId);
            } else {
                logger.info("Device already exists: " + deviceId);
            }
        }
    }
}